﻿@model ValueTuple<IEntity, DataField>
@using NewLife;
@using NewLife.Cube
@using XCode;
@using XCode.Configuration;
@{
    var entity = Model.Item1;
    var field = Model.Item2;

    var fs = ViewBag.Fields as FieldCollection;
    var set = NewLife.Cube.CubeSetting.Current;
    var map = field.MapProvider;

    // 如果没有外部关联，输出数字编辑框和标签
    // 如果映射目标列表项过多，不能使用下拉
    var fact = map == null ? null : EntityFactory.CreateFactory(map.EntityType);

}
@if (map == null || fact != null && fact.Session.Count > set.MaxDropDownList)
{
    var label = entity[field.Name];
    if (label is DateTime dt) label = dt.ToFullString("");
    if (!field.MapField.IsNullOrEmpty())
    {
        var fi = entity.GetType().AsFactory().Table.FindByName(field.MapField) as FieldItem;
        if (fi != null) field = fs.Create(fi);
    }

    @await Html.PartialAsync("_Form_Editor", new ItemModel(field.Name, entity[field.Name], field.Type){Length=field.Length})
    <text>&nbsp;</text>
    <label class="">@label</label>
}
else
{
    // 为该字段创建下拉菜单
    var dic = map?.GetDataSource();
    if (dic != null)
    {
        // 表单页的映射下拉，开头增加无效值选项
        if (fact != null && !map.Key.IsNullOrEmpty())
        {
            if (fact.Table.FindByName(map.Key) is FieldItem fi && fi.Type.IsInt())
            {
                var dic2 = new Dictionary<Object, String>();
                if (!dic.ContainsKey(0))
                {
                    dic2[0] = "<无>";
                    foreach (var item in dic)
                    {
                        dic2[item.Key] = item.Value;
                    }
                    dic = dic2;
                }
            }
        }
        var dic3 = dic.ToDictionary(e => e.Key + "", e => e.Value);

        //@Html.ForDropDownList(field.MapField, dic, entity[field.MapField])
        @await Html.PartialAsync("_Form_DropDownList", new ListBoxModel(field.MapField, dic3,  entity[field.MapField] + ""))
    }
}